# -*- coding: utf-8 -*-
from xadmin import site
from mptt.forms import MPTTAdminForm, TreeNodeChoiceField
from mptt.models import MPTTModel
from xadmin.views import BaseAdminPlugin

from xadmin.views import ListAdminView
from xadmin.views import ModelFormAdminView


class MPTTListPlugin(BaseAdminPlugin):
    mptt_level_indent = 20
    def init_request(self, *args, **kwargs):
        return self.model and issubclass(self.model, MPTTModel)

    def get_ordering(self, __):
        tree_id = self.model._mptt_meta.tree_id_attr
        left = self.model._mptt_meta.left_attr
        return (tree_id, left)

    def result_item(self, __, obj, field_name, row):
        is_display = row['is_display_first']
        item = __()
        if is_display and not row['is_display_first']:
            tmp = u'<div style="text-indent:%dpx">%%s</div>' % (self.mptt_level_indent * obj.get_level())
            # item.wraps.append(u'%s %%s' % ('&nbsp;&nbsp;&nbsp;' * obj.get_level()))
            item.wraps.append(tmp)
        return item

    # Media
    def get_media(self, media):
        # media.add_css({'screen': [self.static('xadmin/css/aggregation.css'),]})
        return media


class MPTTFormPlugin(BaseAdminPlugin):
    raw_id_fields = ()
    def init_request(self, *args, **kwargs):
        result = self.model and issubclass(self.model, MPTTModel)
        if result:
            self.admin_view.form = MPTTAdminForm
        return result

    def get_field_attrs(self, attrs, db_field, **kwargs):
        from mptt.models import MPTTModel, TreeForeignKey
        if db_field.remote_field and issubclass(db_field.remote_field.model, MPTTModel) \
                and not isinstance(db_field, TreeForeignKey) \
                and not db_field.name in self.raw_id_fields:
            attrs.update(dict(form_class=TreeNodeChoiceField, queryset=db_field.remote_field.model.objects.all(), required=False))
        return attrs


site.register_plugin(MPTTListPlugin, ListAdminView)
site.register_plugin(MPTTFormPlugin, ModelFormAdminView)
